package com.guw.AWT;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestActionEvent2 {
    public static void main(String[] args) {
        //两个按钮,实现同一个监听
        //类似的,多个按钮可以实现同一个监听的共用
        Frame f = new Frame("开始-停止");
        Button b1 = new Button("start");
        Button b2 = new Button("stop");

        //设置事件命令,点击时出现该字符串
        b2.setActionCommand("b2-stop");
        b1.setActionCommand("b1-start");

        //两个按钮使用同一个监听事件
        MyMonitor myMonitor = new MyMonitor();
        b1.addActionListener(myMonitor);
        b2.addActionListener(myMonitor);

        f.add(b1,BorderLayout.NORTH);
        f.add(b2,BorderLayout.SOUTH);

        f.pack();
        f.setVisible(true);
        windowClose(f);
    }

    private static void windowClose(Frame f){
        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }
}

//新建一个事件监听的类用于监听
class MyMonitor implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        //获得按钮设置的信息
        System.out.println("按钮被点击了"+e.getActionCommand());
    }
}